import {Injectable} from "@angular/core";
import {Headers, Http, RequestOptions, Response} from "@angular/http";
import {config} from "../config/constants";
import {Observable} from "rxjs/Rx";


@Injectable()
export class CommonService {

  constructor(private http: Http) {

  }

  getData(condition: string): Observable<any> {
    let headers = new Headers({
      'X-WX-Token': config.token,
      'Source': config.source
    });

    let url = config.serviceUrl + condition;
    let options = new RequestOptions({headers: headers});

    return this.http.get(url, options).map(this.extractData).catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    if (body.status != 200) {
      alert(body.errorMsg);
      return;
    } else {
      return body.data || {};
    }
  }


  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.log(errMsg);
    return Observable.throw(error);
  }

  addData(data: any): Observable<any> {
    let body = JSON.stringify(data);
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let url = '';
    return this.http.post(url, body, options).map(response => console.log(response)).catch(this.handleError);
  }

  getDataPromise(): Promise<any> {
    let url = '';
    return this.http.get(url).toPromise().then((res: Response) => {
      let body = res.json();
      return body.data || {};
    }).catch(this.handleError);
  }

  postData(condition: string, num: string, type: number): Observable<any> {
    let headers = new Headers({
      'X-WX-Token': config.token,
      'Source': config.source
    });

    let url = config.serviceUrl + condition;
    let authCode = {
      cellphone: num,
      sendType: type
    };

    let bindPhone = {
      cellphone: num,
      code: type
    };

    let body = (type === 1) ? authCode : bindPhone;

    let options = new RequestOptions({headers: headers});

    return this.http.post(url, body, options).map(this.extractData).catch(this.handleError);

  }
}
